package com.chushouya.aop;

import com.chushouya.common.annotations.AuthSkip;
import com.chushouya.common.support.Contexts;
import com.chushouya.common.support.DevOption;
import com.chushouya.common.support.RequestUserContext;
import com.general.framework.core.lang.Jsons;
import com.general.framework.core.utils.ThreadContext;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 权限拦截切面基类
 * @author chushouya team
 */
@Slf4j
@Component
public abstract class BaseAuthAspect<T> {

    protected void setDevUserContext() {
        final RequestUserContext devUserContext = DevOption.buildDevUserContext();
        log.debug("==>DevUserContext:{}", Jsons.toJsonString(devUserContext));
        ThreadContext.putValue(Contexts.REQUEST_USER_CONTEXT_KEY, devUserContext);
    }

    protected void setUserContext(T userAuth) {
        ThreadContext.putValue(Contexts.REQUEST_USER_CONTEXT_KEY, buildUserContext(userAuth));
    }

    protected void clearUserContext(){
        ThreadContext.removeValue(Contexts.REQUEST_HEADER_CONTEXT_KEY);
    }

    protected abstract RequestUserContext buildUserContext(T userAuth);

    boolean skipAuthValidate(ProceedingJoinPoint joinPoint) {
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        final AuthSkip skipAuth = method.getAnnotation(AuthSkip.class);
        return Objects.nonNull(skipAuth);
    }

}
